package com.itic.mall.mobile.wuliu;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.orderexpress.persistence.model.OrderExpress;
import com.itic.mall.system.orderexpress.persistence.model.OrderExpressExample;
import com.itic.mall.system.orderexpress.service.OrderExpressService;
import com.itic.mall.system.orderproducts.persistence.model.OrderProducts;
import com.itic.mall.system.orderproducts.persistence.model.OrderProductsVo;
import com.itic.mall.system.orderproducts.service.OrderProductsService;
import com.itic.mall.system.product.persistence.model.Product;
import com.itic.mall.system.product.service.ProductService;
import com.itic.mall.system.user.persistence.model.MallUser;

import net.sf.json.JSONObject;
/**
 * 友惠家商城中心接口类
 * @author 许小宝
 * 2017年07月25日  14时11分
 */
@Controller
@RequestMapping(value="/mobile/wuliu")
public class MallWuliuInterface
     extends BaseMobileInterface {
	public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
	//配置您申请的KEY
    public static final String APPKEY ="*************************";
    
    @Autowired
    private OrderExpressService orderExpressService;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderProductsService orderProductsService;
    
    /**
     * 用户根据订单项获得物流信息
     * @param request
     * @param response
     * @param token
     * @param orderProductsId
     * @return
     */
    @RequestMapping(value="getWuliuProdcut")
	@ResponseBody
    public Map<String,Object> getWuliuProdcut( HttpServletRequest request,HttpServletResponse response, String token, String orderProductsId ){
		Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String result = FAIL;
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	try{
	   		//判断必要的参数
	   		if( StringHelper.isNotBlank(token) &&  StringHelper.isNotBlank(orderProductsId) ){
	   			MallUser user = getMallUserByToken(token);
	   			Map<String, Object> dataMap = new HashMap<String,Object>();
	   			if( null != user ){
	   				//添加商品信息
	   				OrderProducts orderProducts = orderProductsService.get(orderProductsId);
	   				Product product = productService.get(orderProducts.getProductId());
	   				
	   				OrderProductsVo vo = new OrderProductsVo();
	   				vo.setId(product.getId());
	   				vo.setMainImageUrl(product.getMainImageUrl());
	   				vo.setIsFreePost(product.getIsFreePost()==""?"001":product.getIsFreePost());
	   				vo.setIsServenBack(product.getIsServenBack()==""?"001":product.getIsServenBack());
	   				vo.setName(product.getName());
	   				vo.setProductHongbao(product.getProductHongbao());
	   				vo.setTotalCount(orderProducts.getTotalCount());
	   				vo.setProductPrice(product.getProductPrice());
	   				vo.setProductOrginPrice(product.getProductOrginPrice());
	   				vo.setTotalMoney(orderProducts.getTotalMoney());
	   				vo.setCreateTime(orderProducts.getCreateTime());
	   				
	   				dataMap.put("product", vo);
	   				
	   				//添加物流信息
	   				String key = APPKEY;
	   				String byKey = sysSettingService.getByKey("MALL_WULIU_KEY");
	   				if( StringHelper.isNotBlank(byKey) ){
	   					key = byKey;
	   				}
	   				OrderExpressExample example = new OrderExpressExample();
	   				example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andOrderProductsIdEqualTo(orderProductsId);
	   				List<OrderExpress> list = orderExpressService.list(example);
	   				
	   				if( list.size() > 0 ){
	   					OrderExpress express = list.get(0);
	   					Object data = getRequest1( key, express.getExpressName(), express.getExpressNum() );
	   					dataMap.put("wuliuNum", express.getExpressNum());
		   				dataMap.put("wuliuType", outCommonService.getNameByCode("T_MALL_ORDER_WULIU",  express.getExpressName()));
	   					dataMap.put("wuliu", data);
	   				}else{
	   					dataMap.put("wuliu", null);
	   				}
	   				
	   				
	   				resultMap.put(DATA, dataMap);
	   				result = SUCCESS;
	   			    errorCode = SUCCESS_ERROR_CODE;
	   			 	errorMsg = SUCCESS_ERROR_MSG; 
	   			}else{
					result = LOGIN;
	    			errorCode = LOGIN_ERROR_CODE;
	            	errorMsg = LOGIN_ERROR_MSG;  	
				}
			}
	   		
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallWuliuInterface", "getWuliuProdcut", e.toString(),"用户根据订单项获得物流信息",e);
		}
		resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
    }
	
    
	@RequestMapping(value="getWuliuMsg")
	@ResponseBody
    public Map<String,Object> getWuliuMsg( HttpServletRequest request,HttpServletResponse response, String token, String orderProductsId ){
		Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String result = FAIL;
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	try{
	   		//判断必要的参数
	   		if( StringHelper.isNotBlank(token) &&  StringHelper.isNotBlank(orderProductsId) ){
	   			MallUser user = getMallUserByToken(token);
	   			if( null != user ){
	   				String key = APPKEY;
	   				String byKey = sysSettingService.getByKey("MALL_WULIU_KEY");
	   				if( StringHelper.isNotBlank(byKey) ){
	   					key = byKey;
	   				}
	   				
	   				OrderExpressExample example = new OrderExpressExample();
	   				example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andOrderProductsIdEqualTo(orderProductsId);
	   				List<OrderExpress> list = orderExpressService.list(example);
	   				if( list.size() > 0 ){
	   					OrderExpress express = list.get(0);
	   					Object data = getRequest1( key, express.getExpressName(), express.getExpressNum() );
		   				resultMap.put(DATA, data);
		   				result = SUCCESS;
		   			    errorCode = SUCCESS_ERROR_CODE;
		   			 	errorMsg = SUCCESS_ERROR_MSG; 
	   				}else{
		   				result = FAIL;
		   			    errorCode = NONE_EXPRESS_ERROR_CODE;
		   			 	errorMsg = NONE_EXPRESS_ERROR_MSG; 
	   				}
	   				
	   			}else{
					result = LOGIN;
	    			errorCode = LOGIN_ERROR_CODE;
	            	errorMsg = LOGIN_ERROR_MSG;  	
				}
			}
	   		
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallWuliuInterface", "getWuliuMsg", e.toString(),"用户根据订单项获得物流信息",e);
			
		}
		resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
    }
	
    //1.常用快递查询API
    public static Object getRequest1( String key, String wuliuType, String wuliuNum ){
    	Object result = null;
        String url ="http://v.juhe.cn/exp/index";//请求接口地址
        Map<String,Object> params = new HashMap<String,Object>();//请求参数
            params.put("com",wuliuType);//需要查询的快递公司编号
            params.put("no",wuliuNum);//需要查询的订单号
            params.put("key",key);//应用APPKEY(应用详细页查询)
            params.put("dtype","json");//返回数据的格式,xml或json，默认json
 
        try {
            result =net(url, params, "GET");
            JSONObject object = JSONObject.fromObject(result);
            if(object.getInt("error_code")==0){
            	JSONObject object2 = object.getJSONObject("result");
            	Object object3 = object2.get("list");
                result = object3;
            }else{
                result = object.get("error_code")+":"+object.get("reason");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
 
 
    /**
     *
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return  网络请求字符串
     * @throws Exception
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	public static String net(String strUrl, Map params,String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if(method==null || method.equals("GET")){
                strUrl = strUrl+"?"+urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if(method==null || method.equals("GET")){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params!= null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                        out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }
 
    //将map型转为请求参数型
    @SuppressWarnings("rawtypes")
	public static String urlencode(Map<String,Object>data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}